﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.WeChat.CardVoucher.Entity;
using NewRetail.Application.Components.WeChat.CardVoucher.Model;
using NewRetail.Application.Components.WeChat.CardVoucher.Services;
using NewRetail.Application.Core;
using NewRetail.Application.Utility;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace NewRetail.Api.Controllers.WeChatControllers
{
    /// <summary>
    /// 券对应积分
    /// </summary>
    [NewRetailRoute("wechat-cardvoucherintegral")]
    public class WeChatCardVoucherIntegralController : BaseController<CardVoucherIntegralInfo, CardVoucherIntegralPagingDto>
    {
        #region Field
        public readonly ICardVoucherService _cardVoucherService;
        private readonly ILogger _logger;
        #endregion

        #region Constructor
        public WeChatCardVoucherIntegralController(ICardVoucherService cardVoucherService, ILogger<WeChatCardVoucherIntegralController> logger)
        {
            _cardVoucherService = cardVoucherService;
            _logger = logger;
        }
        #endregion

        #region method

        #region 代金券对应兑换积分设置
        /// <summary>
        /// 代金券对应兑换积分设置
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-savemarketingfavorintegralmultiple")]
        public async Task<ResponseEntity<CardVoucherIntegralInfo[]>> SaveMarketingFavorIntegralMultiple([FromBody] CardVoucherIntegralInfo[] inputData)
        {
            inputData.Should().NotBeNullOrEmpty();
            using var uow = this.UnitOfWorkManager.Begin(requiresNew: true, isTransactional: true);
            try
            {
                var db = await this.Repo.GetDbContextAsync();
                var cardVoucherIntegralSet = db.Set<CardVoucherIntegralInfo>();

                foreach (var m in inputData)
                {
                    if (string.IsNullOrWhiteSpace(m.Id))
                    {
                        await this.BeforeInsertDataInitial(m);
                        this.EntityHelper.InitEntity(m);
                        await this.BeforeInsert(m);
                        cardVoucherIntegralSet.Add(m);
                    }
                    else
                    {
                        var entity = await cardVoucherIntegralSet.FirstOrDefaultAsync(x => x.Id == m.Id);
                        if (entity == null)
                        {
                            throw new UserFriendlyException("更新的对象不存在");
                        }
                        await this.BeforeUpdate(entity, m);
                        this.EntityHelper.SetUpdationInfo(entity);
                    }                   
                }

                await db.SaveChangesAsync();

                await uow.CompleteAsync();
                return new ResponseEntity<CardVoucherIntegralInfo[]>().SetData(inputData);
            }
            catch
            {
                await uow.RollbackAsync();
                throw;
            }
        }
        #endregion

        #region 分页查询券详情
        /// <summary>
        /// 分页查询券详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public override async Task<ResponseEntity<PagedResultDto<CardVoucherIntegralInfo>>> QueryPaging([FromBody] CardVoucherIntegralPagingDto dto)
        {
            var res = await base.QueryPaging(dto);
            
            if (res?.Data?.Items?.Any() ?? false)
            {
                //res.Data.Items = await _cardVoucherService.AttachCardVoucher(res.Data.Items.ToArray());
                var retItems = await _cardVoucherService.AttachCardVoucher(res.Data.Items.ToArray());
                res.Data.Items = retItems.Where(x => x.CardVoucherInfo != null).ToArray();
                res.Data.TotalCount = res.Data.Items.Count;
            }
            return res;
        }
        #endregion

        #endregion

        #region other

        #region 根据条件查询（继承的BaseController类里面QueryPaging调用FilterQueryPaging用下面的覆盖执行）
        protected override async Task<IQueryable<CardVoucherIntegralInfo>> FilterQueryPaging(DbContext db, IQueryable<CardVoucherIntegralInfo> query, CardVoucherIntegralPagingDto dto)
        {
            if (!string.IsNullOrWhiteSpace(dto.stockId))
            {
                query = query.Where(x => x.stockId == dto.stockId);
            }

            await Task.CompletedTask;
            return query;
        }
        #endregion

        #endregion
    }
}
